using System.Collections;
using UnityEngine;

namespace PKGames.AssetBundleSystem
{
	public class AssetLoadRequest<T> : IEnumerator where T : Object
	{
		private string _assetName = string.Empty;

		private AssetBundleRequest _assetBundleRequest;

		private bool _isDone;

		private T _asset;

		public T Asset => _asset;

		public object Current => null;

		public AssetLoadRequest(AssetBundle assetBundle, string assetName)
		{
			if (assetBundle != null)
			{
				_assetName = assetName;
				_assetBundleRequest = assetBundle.LoadAssetAsync(_assetName, typeof(T));
				return;
			}
			throw new InvalidAssetBundleException($"Invalid AssetBundle \"{assetName}\" is null");
		}

		public bool MoveNext()
		{
			return Update();
		}

		public void Reset()
		{
		}

		private bool Update()
		{
			if (IsLoadAssetAsyncFinished())
			{
				_asset = (_assetBundleRequest.asset as T);
				_isDone = true;
			}
			return !_isDone;
		}

		private bool IsLoadAssetAsyncFinished()
		{
			return _assetBundleRequest != null && _assetBundleRequest.isDone;
		}
	}
}
